//
//  CWTabbar.swift
//  CWWeibo06
//
//  Created by ycw on 2017/7/22.
//  Copyright © 2017年 xiaowei. All rights reserved.
//

import UIKit

protocol CWTabbarDelegate: NSObjectProtocol {
    func CWtabbarDelegate()
}

class CWTabbar: UITabBar {
    
    //声明闭包用来跳转控制器
    var composeCallBack: (()->())?
    
    //声明协议属性
    weak var tabbarDelegate: CWTabbarDelegate?
    
    //MARK: 懒加载button
    private lazy var button: UIButton = {
        
        let btn: UIButton = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        btn.sizeToFit()
        
        //添加按钮点击事件
        btn.addTarget(self, action: #selector(didClickButton), for: .touchUpInside)
        
        return btn
        
    }()

    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func setupUI() {
        
        addSubview(button)
        
    }
    
     //MARK: 添加按钮的点击事件
    @objc private func didClickButton() {
        
        composeCallBack?()
        
        tabbarDelegate?.CWtabbarDelegate()
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        button.centerX = width / 2
        
        button.centerY = height / 2 - 5
        
        //设置button的宽度
        let buttonWidth = width / 5

        
        //记录按钮个数的索引值
        var index: Int = 0
        
        
        //遍历子视图，获取系统控件的类型
        for subView in subviews {
            
            //print(subviews)
            
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                subView.width = buttonWidth
                
                subView.x = CGFloat(index) * buttonWidth
                
                index += 1
                
                if index == 2 {
                    index += 1
                }
                
            }
            
        }
    }
    
   
    
    
    //MARK: 使用drewRect方法也可以布局
//    override func draw(_ rect: CGRect) {
//        super.draw(rect)
//        
//        button.center.x = self.frame.size.width / 2
//        
//        button.center.y = self.frame.size.height / 2
//        
//    }

}
